# -*- coding: utf-8 -*-

"""
1.try to read the post from bot,and store it
2.query the subscribers,and make mail task as <post,recepts>
3.for recpt in recpts:
    mail(post,recpt)

"""
import wsgiref.handlers
import xmw
from xmw.db import ds
from xmw.db import counter
from google.appengine.ext import webapp
from google.appengine.ext import db
import urllib
from xmw import error

import logging
from xmw.db import user_mgr
import xmlrpclib
import global_setting


class MainPage(xmw.RequestHandler):
    s = xmlrpclib.Server('http://xmw-bot-4.appspot.com/xml_rpc_service')
    def set_base(self):
        post_seq_min=self.s.post_mgr.get_seq_min()
        if post_seq_min is not None:
            base    =int(post_seq_min)-1
            c=counter.PostCounter()
            c.reset(base)
            msg="set PostCounter to %d"%base
            logging.info(msg)
            self.response.out.write(msg)
        return
        
    """        
    def get_thread_subscribers_mail(self,thread_id):
        logging.info("query subscriber's mail for %s"%thread_id)
        s_q=ds.Sub_Req.all()
        s_q.filter('thread_id =',thread_id)
        s_q.filter('status =',ds.Sub_Req_Status.IN_TRACE)
        lst_sub=s_q.fetch(1000)
        
        lst_mail=[]
        for sub in lst_sub:
            user_q=ds.User.all()
            user_q.filter('user_id =',sub.user_id)
            logging.info('user_id=%d',sub.user_id)
            #user_q.filter('status =',ds.Sub_Req_Status.IN_TRACE)
            user = user_q.get()
            if user is not None:
                logging.info('got email:%s'%user.email)
                lst_mail.append(str(user.email))
            else:
                logging.info('got no email')
        
        return lst_mail
    
    """
    def get_thread_subscribers_mail(self,post_task):
        logging.info("query subscriber's mail for %s"%post_task.thread_id)
        s_q=ds.Sub_Req.all()
        s_q.filter('thread_id =',post_task.thread_id)
        s_q.filter('status =',ds.Sub_Req_Status.IN_TRACE)
        lst_sub=s_q.fetch(1000)
        
        lst_mail=[]
        for sub in lst_sub:
            #if see chrAuthor only,while current post author is not chrAuthor,ignore it
            if sub.option==ds.Sub_Req_Option.chrAuthor_Only:
                if post_task.author != post_task.chrAuthor:
                    continue
                
            user_q=ds.User.all()
            user_q.filter('user_id =',sub.user_id)
            logging.info('user_id=%d',sub.user_id)
            #user_q.filter('status =',ds.Sub_Req_Status.IN_TRACE)
            user = user_q.get()
            if user is not None:
                logging.info('got email:%s'%user.email)
                lst_mail.append(str(user.email))
            else:
                logging.info('got no email')
        
        return lst_mail
    def get_chrAuthor(self,thread_id):
        t_q=xmw.Thread.all()
        t_q.filter('thread_id =', thread_id)
        thread=t_q.get()
        if thread is not None:
            return thread.chrAuthor
        else:
            return None
      
    
    def get(self):
        (is_init,e) = self.get_key_from_GET("init")
        if is_init is not None:
            self.set_base()
            return
        
        #now comes to the main issues
        c=counter.PostCounter()
        base=c.get_count()
        logging.info('query post base=%d,n=5'%(base))
        lst_post_dict=self.s.post_mgr.get_lst_post(base,5)
        logging.info(lst_post_dict)
        cnt=0
        min_seq=2147483647
        
        #first adjust the counter
        for post_dict in lst_post_dict:
            seq=post_dict['seq']
            if seq<min_seq:
                min_seq=seq
        if min_seq != 2147483647:
            #post processed
            base=c.get_count()
            if base<min_seq:
                logging.warning('adjust counter to %d,orginal %d'%(min_seq,base))
                c.reset(base=min_seq)
        
        for post_dict in lst_post_dict:
            thread_id=post_dict['thread_id']
            
            p_t= ds.Post_Task()
            author=xmw.xmw_decoding(post_dict['author']).decode('utf-8')
            
            
            p_t.author=author
            p_t.date=xmw.ascii_to_datetime(str(post_dict['date']))
            p_t.floor=post_dict['floor']
            content=post_dict['content']
            
            content =xmw.xmw_zip_decoding(content)
            p_t.content=content.decode('utf-8')
            p_t.url=post_dict['url'].encode('ascii')
            p_t.post_id=post_dict['post_id']
            p_t.thread_id=post_dict['thread_id']
            
            p_t.title = xmw.xmw_decoding(post_dict['title']).decode('utf-8')
            p_t.offset = post_dict['offset']
            p_c =counter.PostTaskCounter()
            p_t.seq=p_c.inc_and_get()
            p_t.chrAuthor=self.get_chrAuthor(p_t.thread_id)
            
            lst_mail=self.get_thread_subscribers_mail(p_t)
            
            p_t.lst_mail=lst_mail
            
            line10=u"""
<br>
--------------------------<br>
<table border="0">
<tr>
    <td>楼主：</td><td>               %s<br>    </td>
</tr>
<tr>        
    <td>原贴链接：</td><td>        <a href=%s>%s</a> <br/> </td>
</tr>
</table>
--------------------------<br>    """%(p_t.chrAuthor,p_t.url,p_t.url)
            #line11=u"""标题: %s\n
            #"""%p_t.title
            
            line1=line10.encode('utf-8')
            #line1=u""""""
            #line1=line11.encode('utf-8')+line1
            
            line2=u"""
\n回帖人:<b>%s</b>  日期:%s                        """%(p_t.author,p_t.date)
            if p_t.floor is not None:
                line2=line2+u""" %s（楼）    """%(p_t.floor)
            line2=line2+u"""<br>"""
            
            line3=u"""<br />
%s
            """%p_t.content
            #body=line1
            body=""+line2.encode('utf-8')
            body=body+line3.encode('utf-8')
            body=body+line1
            #body="""
            #----------------------------
            #            标题：<a href=%s>%s</a>            
            #----------------------------
            #            作者:%s  日期:%s                        %s（楼）
            #----------------------------
            #%s
            #"""%(p_t.url,p_t.title,p_t.author,p_t.date,p_t.floor,p_t.content)
            reply=u"回复作者："
            #owner=""
            if p_t.author == p_t.chrAuthor:
                reply=u"楼主更新"
            else:
                reply=u"网友回复"
            
            #if no subscriber,ignor it
            if len(p_t.lst_mail)>0:    
                #subject=(u"[天涯- "+reply+u"] "+u"( "+p_t.author+u" ) "+p_t.title)
                #subject=(u"[天涯- "+reply+u"] "+u"("+p_t.author+u") "+p_t.title)
                #subject=(u"[天涯-"+reply+u"] "+p_t.title+u" - " +p_t.author+"<!--%s-->"%thread_id)
                subject=(u"[天涯-"+reply+u"] "+p_t.title+u" - " +p_t.author)
                logging.info('call mailer to send mail:\n Recepts:%s\n Subject:%s\n'%(str(p_t.lst_mail),subject))
                xmw.send_mail(p_t.lst_mail,xmw.xmw_encoding(subject.encode('utf-8')), xmw.xmw_zip_encoding(body))
            
            #do not need to store mail info local
            #p_t.put()
            #c=counter.PostCounter()
            c.inc_and_get()
            cnt=cnt+1
            
        
        
        
        e=error.OK("%d post processed"%cnt)
        self.render_error(e)
        
def main():
  application = webapp.WSGIApplication(
                                       [('/robot/post_mailer', MainPage)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()